// 缓存服务
class CacheService {
  constructor() {
    this.cache = new Map()
    this.expireTime = 5 * 60 * 1000 // 5分钟过期
    this.priorities = {
      quick: 1,        // 快捷统计优先级最高
      trade: 2,        // 交易统计次之
      member: 2,       // 会员统计次之
      region: 3,       // 地区分布
      good: 3,         // 商品统计
      order: 3,        // 订单统计
      coupon: 3,       // 优惠券统计
      income_expense: 4 // 收支统计优先级最低
    }
    this.preloadQueue = new Set()
  }

  // 设置缓存
  set(key, data, priority = 0) {
    this.cache.set(key, {
      data,
      timestamp: Date.now(),
      priority: priority || this.priorities[key.split('_')[0]] || 5
    })
  }

  // 获取缓存
  get(key) {
    const cacheItem = this.cache.get(key)
    if (!cacheItem) return null

    // 检查是否过期
    if (Date.now() - cacheItem.timestamp > this.expireTime) {
      this.cache.delete(key)
      return null
    }

    return cacheItem.data
  }

  // 清除缓存
  clear() {
    this.cache.clear()
    this.preloadQueue.clear()
  }

  // 清除指定key的缓存
  remove(key) {
    this.cache.delete(key)
    this.preloadQueue.delete(key)
  }

  // 检查缓存是否存在且未过期
  has(key) {
    const cacheItem = this.cache.get(key)
    if (!cacheItem) return false
    return Date.now() - cacheItem.timestamp <= this.expireTime
  }

  // 添加到预加载队列
  addToPreloadQueue(key) {
    this.preloadQueue.add(key)
  }

  // 从预加载队列中移除
  removeFromPreloadQueue(key) {
    this.preloadQueue.delete(key)
  }

  // 获取预加载队列
  getPreloadQueue() {
    return Array.from(this.preloadQueue)
  }

  // 清理过期缓存
  cleanup() {
    const now = Date.now()
    for (const [key, value] of this.cache.entries()) {
      if (now - value.timestamp > this.expireTime) {
        this.cache.delete(key)
      }
    }
  }

  // 获取缓存状态
  getStatus() {
    return {
      total: this.cache.size,
      preloadQueue: this.preloadQueue.size,
      priorities: Object.entries(this.priorities).map(([key, priority]) => ({
        key,
        priority,
        cached: Array.from(this.cache.keys()).filter(k => k.startsWith(key)).length
      }))
    }
  }
}

export const cacheService = new CacheService() 